<template>
  <div class="model-base-container">
    <!-- 搜索 + 操作按钮区域 -->
    <div class="search-action-bar">
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="基模名称">
          <el-input
            v-model="searchForm.modelName"
            placeholder="请输入基模名称"
            clearable
          />
        </el-form-item>
        <el-form-item label="是否叶子节点">
          <el-select v-model="searchForm.isLeaf" placeholder="是否叶子节点" clearable>
            <el-option label="是" value="1" />
            <el-option label="否" value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="warning" @click="resetQuery">重置</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="handleAdd">新增</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 表格展示区域（带加载状态） -->
    <el-table
      :data="tableData"
      style="width: 100%"
      max-height="500"
      border
      stripe
      v-loading="tableLoading"
      element-loading-text="数据加载中..."
      element-loading-spinner="el-icon-loading"
      element-loading-background="rgba(255, 255, 255, 0.8)"
    >
      <el-table-column
        prop="baseId"
        label="基模ID"
        width="100"
      />
      <el-table-column
        prop="parentId"
        label="父级ID"
        width="100"
      />
      <el-table-column
        prop="modelName"
        label="基模名称"
        width="180"
      />
      <el-table-column
        prop="modelPath"
        label="模型路径"
        width="220"
        show-overflow-tooltip
      />
      <el-table-column
        prop="isLeaf"
        label="是否叶子节点"
        width="120"
        :formatter="formatIsLeaf"
      />
      <el-table-column
        prop="createTime"
        label="创建时间"
        width="180"
        :formatter="formatDate"
      />
      <el-table-column
        prop="updateTime"
        label="更新时间"
        width="180"
        :formatter="formatDate"
      />
      <el-table-column fixed="right" label="操作" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            @click="handleEdit(scope.row)"
          >
            修改
          </el-button>
          <el-button
            size="mini"
            type="danger"
            @click="handleDelete(scope.row)"
          >
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页区域 -->
    <div class="pagination-bar">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pageDto.page"
        :page-sizes="[5, 10, 20, 30, 50]"
        :page-size="pageDto.size"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      />
    </div>
    <!-- 新增/修改弹窗 -->
    <el-dialog
      title="新增/修改基础模型"
      :visible.sync="dialogVisible"
      width="40%"
      @close="handleDialogClose"
    >
      <el-form :model="form" :rules="rules" label-width="120px" ref="formRef">
        <el-form-item label="基模ID" prop="baseId">
          <el-input v-model.number="form.baseId" disabled />
        </el-form-item>
        
        <!-- 父级ID选择区域（带选择器） -->
        <el-form-item label="父级ID" prop="parentId">
          <div class="parent-id-row">
            <el-input
              v-model.number="form.parentId"
              placeholder="输入ID或点击选择"
              style="flex: 1; margin-right: 8px"
            />
            <span
              v-if="relatedParentName"
              class="related-parent-name"
              style="margin: 0 8px; line-height: 32px"
            >
              {{ relatedParentName }}
            </span>
            <el-button
              type="primary"
              icon="el-icon-search"
              style="min-width: 100px"
              @click="openParentSelector"
            >
              选择父级
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="基模名称" prop="modelName">
          <el-input v-model="form.modelName" />
        </el-form-item>
        <el-form-item label="模型路径" prop="modelPath">
          <el-input v-model="form.modelPath" />
        </el-form-item>
        <el-form-item label="是否叶子节点" prop="isLeaf">
          <el-select v-model="form.isLeaf" placeholder="请选择是否叶子节点">
            <el-option label="是" value="1" />
            <el-option label="否" value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="warning" @click="dialogVisible = false">取消</el-button>
        <el-button type="success" @click="handleSave">确定</el-button>
      </div>
    </el-dialog>
    <ModelBaseSelector
      :visible.sync="parentSelectorVisible"
      @selected="handleParentSelected"
      @close="parentSelectorVisible = false"
    />
    <!-- 删除确认弹窗 -->
    <el-dialog
      title="删除确认"
      :visible.sync="deleteVisible"
      width="30%"
    >
      <p>确定要删除该基础模型记录吗？此操作不可逆</p>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="deleteVisible = false">取消</el-button>
        <el-button type="danger" @click="confirmDelete">确定删除</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
// 引入父级选择器组件
import ModelBaseSelector from "../TableOrForms/ModelBaseSelector.vue";
export default {
  name: 'ModelBaseTable',
  components: {
    ModelBaseSelector // 注册选择器组件
  },
  data() {
    return {
      searchForm: {}, // 搜索表单数据
      pageDto: {
        page: 1,
        size: 10,
        modelBaseModels: {} 
      },
      total: 0, // 总数据量
      tableData: [], // 表格数据
      // 弹窗状态
      dialogVisible: false,
      parentSelectorVisible: false,
      deleteVisible: false,
      deleteId: null, // 待删除ID
      form: {}, // 新增/修改表单数据
      relatedParentName: "", // 父级ID关联的名称
      tableLoading: false, // 表格加载状态
      // 表单校验规则
      rules: {
        parentId: [
          { required: true, message: '请输入父级ID', trigger: 'blur' },
          { type: 'number', message: '请输入数字值', trigger: 'blur' }
        ],
        modelName: [
          { required: true, message: '请输入基模名称', trigger: 'blur' },
          { min: 1, max: 50, message: '名称长度需在1-50字符之间', trigger: 'blur' }
        ],
        modelPath: [
          { message: '请输入模型路径', trigger: 'blur' }
        ],
        isLeaf: [
          { required: true, message: '请选择是否叶子节点', trigger: 'change' }
        ]
      }
    };
  },
  methods: {
    // 格式化日期显示
    formatDate(row, column) {
      const date = row[column.property];
      return date ? new Date(date).toLocaleString() : '';
    },
    // 格式化是否叶子节点（0-否，1-是）
    formatIsLeaf(row) {
      return row.isLeaf === 1 ? '是' : '否';
    },
    // 分页大小改变
    handleSizeChange(val) {
      this.pageDto.size = val;
      this.queryByPage();
    },
    // 当前页改变
    handleCurrentChange(val) {
      this.pageDto.page = val;
      this.queryByPage();
    },
    // 搜索查询（修复搜索失效问题）
    handleQuery() {
      this.pageDto.modelBaseModels.modelName = this.searchForm.modelName;
      this.pageDto.modelBaseModels.isLeaf = this.searchForm.isLeaf;
      this.pageDto.page = 1; // 重置页码
      this.queryByPage();
    },
    // 重置搜索
    resetQuery() {
      this.searchForm = {};
      // 重置分页参数（对齐3.txt的重置逻辑）
      this.pageDto = { page: 1, size: 10, modelBaseModels: {} };
      this.queryByPage();
    },
    // 新增按钮
    handleAdd() {
      this.form = {};
      this.relatedParentName = "";
      this.dialogVisible = true;
      this.parentSelectorVisible = false;
    },
    // 编辑按钮（确保父级名称正确查询）
    handleEdit(row) {
      this.form = { ...row };
      this.relatedParentName = "";
      // 若有父级ID，查询并显示父级名称
      if (row.parentId) {
        this.getParentName(row.parentId);
      }
      this.dialogVisible = true;
      this.parentSelectorVisible = false;
    },
    // 标记删除ID
    handleDelete(row) {
      this.deleteId = row.baseId;
      this.deleteVisible = true;
    },
    // 确认删除
    confirmDelete() {
      this.$api.modelBaseApi
        .deleteById({ id: this.deleteId })
        .then((res) => {
          if (res.data.code === 1) {
            this.$notify.success({ title: '成功', message: '删除成功！' });
            this.deleteVisible = false;
            this.queryByPage(); // 刷新列表
          } else {
            this.$notify.error({ title: '错误', message: res.data.msg || '删除失败' });
          }
        })
        .catch(() => {
          this.$notify.error({ title: '错误', message: '网络异常，请重试' });
        });
    },
    // 保存新增/修改
    handleSave() {
      this.$refs.formRef.validate((valid) => {
        if (valid) {
          const isEdit = !!this.form.baseId;
          const apiMethod = isEdit 
            ? this.$api.modelBaseApi.edit 
            : this.$api.modelBaseApi.add;
          apiMethod(this.form)
            .then((res) => {
              if (res.data.code === 1) {
                this.$notify.success({
                  title: '成功',
                  message: isEdit ? '修改成功！' : '新增成功！'
                });
                this.dialogVisible = false;
                this.queryByPage();
              } else {
                this.$notify.error({
                  title: '错误',
                  message: res.data.msg || (isEdit ? '修改失败' : '新增失败')
                });
              }
            })
            .catch(() => {
              this.$notify.error({ title: '错误', message: '网络异常，请重试' });
            });
        }
      });
    },
    // 分页查询数据
    queryByPage() {
      this.tableLoading = true;
      console.log(this.pageDto);
      this.$api.modelBaseApi
        .queryByPage(this.pageDto)
        .then((res) => {
          if (res.data.code === 1) {
            this.tableData = res.data.data.list || [];
            this.total = res.data.data.total || 0;
          } else {
            this.$notify.error({ title: '错误', message: res.data.msg || '查询失败' });
            this.tableData = [];
            this.total = 0;
          }
        })
        .catch(() => {
          this.$notify.error({ title: '错误', message: '网络异常，请重试' });
          this.tableData = [];
          this.total = 0;
        })
        .finally(() => {
          this.tableLoading = false;
        });
    },
    // 打开父级选择器
    openParentSelector() {
      this.parentSelectorVisible = true;
    },
    // 接收选择器返回的父级数据
    handleParentSelected(parentId, modelName) {
      this.form.parentId = parentId;
      this.relatedParentName = modelName;
      this.parentSelectorVisible = false;
    },
    // 弹窗关闭时重置状态
    handleDialogClose() {
      this.form = {};
      this.relatedParentName = "";
      this.parentSelectorVisible = false;
    },
    // 根据父级ID查询名称
    getParentName(parentId) {
      this.$api.modelBaseApi
        .getById({ id: parentId })
        .then((res) => {
          if (res.data.code === 1) {
            this.relatedParentName = res.data.data.modelName;
          }
        })
        .catch(() => {
          this.relatedParentName = "未知父级";
        });
    }
  },
  // 页面加载时查询数据
  mounted() {
    this.queryByPage();
  }
};
</script>
<style scoped>
.model-base-container {
  padding: 20px;
  background-color: #fff;
  box-shadow: 0 0 8px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  width: 100%;
  box-sizing: border-box;
  min-height: calc(100vh - 40px);
}
.search-action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}
.search-form {
  display: flex;
  align-items: center;
  gap: 10px;
  flex-wrap: wrap; /* 适配小屏幕搜索项换行 */
}
.pagination-bar {
  margin-top: 15px;
  display: flex;
  justify-content: flex-end;
}
/* 父级ID选择行样式 */
.parent-id-row {
  display: flex;
  align-items: center;
  width: 100%;
}
.related-parent-name {
  color: #409eff;
  font-weight: 500;
  white-space: nowrap;
}
.dialog-footer {
  text-align: right;
}
/* 按钮交互效果 */
.el-button {
  transition: all 0.3s ease;
}
.el-button:hover {
  transform: scale(1.05);
}
.el-dialog__body {
  padding: 20px;
  line-height: 1.6;
}
/* 表格样式优化 */
.el-table {
  width: 100% !important;
  table-layout: fixed;
  overflow: auto;
}
.el-table th {
  table-layout: fixed;
}
</style>